package picasa;
import java.util.Iterator;
import java.io.*;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;



public class UploadFileServlet extends HttpServlet {

	public void doPost(HttpServletRequest req,HttpServletResponse res)
	{
		
		try{
			PrintWriter out = res.getWriter();
			databaseConnection conn = new databaseConnection();
			
			FileItemFactory factory = new DiskFileItemFactory();
//			 Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
//			 Parse the request
			List /* FileItem */ items = upload.parseRequest(req);
			String foldername="";
			String userid="";
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				
				FileItem item = (FileItem) iter.next();
				
				if (item.isFormField()) {
					String itemName = item.getFieldName();
					if (itemName.equals("selFolder") | itemName.equals("newFolder")){
						foldername = item.getString();
					}else if(itemName.equals("userid")){
						userid=item.getString();
					}
				} else {
					System.out.println("Field");
					File cfile=new File(item.getName());
					System.out.println(getServletContext().getRealPath("/ImageLibraries/" + foldername + "/"));// this will give u the path upto ROOT folder..if u want to put inside ur own forlder u can give the location inside the quotes
					File tosave=new File(getServletContext().getRealPath("/ImageLibraries/" + foldername + "/"),cfile.getName());
					if(tosave.exists()){
						System.out.println("no field");
					}else{
						conn.addPic(userid,foldername,cfile.getName());
						conn.UpdateNumber(userid,foldername);
						System.out.println("real field");
						item.write(tosave);
					}
				 }
			}
			res.setContentType("text/xml");
			res.setHeader("Cache-Control","no-cache");
			out.println("<response>");
			out.println("<valid>File Upload Sucessfully</valid>");
			out.println("</response>");
			out.close(); 
		}catch(Exception e){System.out.println(e);}
	}
}
